import React, { useRef, useState, useEffect } from 'react';
import { Dialog, Form, Input, Select, Radio, MessagePlugin, Button } from 'tdesign-react';
import { FormInstanceFunctions } from 'tdesign-react/es/form/type';
import { updateUserAPI } from '@/api/user.api';
import { getDepartmentListAPI } from '@/api/department.api';
import { FormRule } from 'tdesign-react/es/form/type';

const { FormItem } = Form;

interface EditDialogProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  userData: any;
}

interface Department {
  id: number;
  name: string;
  code: string;
}

const EditDialog: React.FC<EditDialogProps> = ({ visible, onClose, onSuccess, userData }) => {
  const formRef = useRef<FormInstanceFunctions>();
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);

  // 获取部门列表
  useEffect(() => {
    const fetchDepartments = async () => {
      try {
        setLoading(true);
        const res = await getDepartmentListAPI();
        if (res.data?.data) {
          setDepartments(res.data.data);
        }
      } catch (error) {
        MessagePlugin.error('获取部门列表失败');
      } finally {
        setLoading(false);
      }
    };

    if (visible) {
      fetchDepartments();
    }
  }, [visible]);

  // 表单验证规则
  const rules: Record<string, FormRule[]> = {
    name: [{ required: true, message: '请输入姓名', type: 'error' }],
    role: [{ required: true, message: '请选择角色', type: 'error' }],
    gender: [{ required: true, message: '请选择性别', type: 'error' }],
    phone: [
      { required: true, message: '请输入手机号', type: 'error' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', type: 'error' }
    ],
    email: [
      { required: true, message: '请输入邮箱', type: 'error' },
      { pattern: /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址', type: 'error' }
    ],
    departmentId: [{ required: true, message: '请选择部门', type: 'error' }],
  };

  // 设置初始值
  useEffect(() => {
    const timer = setTimeout(() => {
      // 根据userData的 departmentName 设置部门
      const department = departments.find(dept => dept.name === userData.departmentName);
      if (visible && userData && formRef.current) {
        formRef.current.setFieldsValue({
          studentId: userData.studentId,
          name: userData.name,
          role: userData.role,
          gender: userData.gender,
          phone: userData.phone,
          email: userData.email,
          departmentId: department?.id,
        });
      }
    }, 0);

    return () => clearTimeout(timer);
  }, [visible, userData]);

  // 提交编辑
  const handleSubmit = async () => {
    const valid = await formRef.current?.validate();
    if (valid === true) {
      try {
        setSubmitLoading(true);
        const formData = formRef.current?.getFieldsValue(true);
        if (formData) {
          await updateUserAPI(userData.studentId, formData).then((res) => {
            if (res.status === 200) {
              MessagePlugin.success('更新成功');
              onSuccess();
              onClose();
            } else {
              MessagePlugin.error(res.data?.message || '更新失败');
            }
          })
        }
      } catch (error: any) {
        MessagePlugin.error(error.response?.data?.message || '更新失败');
      } finally {
        setSubmitLoading(false);
      }
    }
  };

  return (
    <Dialog
      header="编辑用户"
      visible={visible}
      onClose={onClose}
      width={600}
      footer={
        <>
          <Button theme="default" onClick={onClose}>
            取消
          </Button>
          <Button theme="primary" loading={submitLoading} onClick={handleSubmit}>
            确定
          </Button>
        </>
      }
    >
      <Form ref={formRef} rules={rules} labelWidth={100}>
        <FormItem label="学/工号" name="studentId">
          <Input disabled />
        </FormItem>
        <FormItem label="姓名" name="name">
          <Input placeholder="请输入姓名" />
        </FormItem>
        <FormItem label="角色" name="role">
          <Select
            options={[
              { label: '学生', value: 'student' },
              { label: '教师', value: 'teacher' },
              { label: '管理员', value: 'admin' },
            ]}
            placeholder="请选择角色"
          />
        </FormItem>
        <FormItem label="性别" name="gender">
          <Radio.Group>
            <Radio value="male">男</Radio>
            <Radio value="female">女</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem label="手机号" name="phone">
          <Input placeholder="请输入手机号" />
        </FormItem>
        <FormItem label="邮箱" name="email">
          <Input placeholder="请输入邮箱" />
        </FormItem>
        <FormItem label="部门" name="departmentId">
          <Select
            loading={loading}
            options={departments.map(dept => ({
              label: `${dept.name} (${dept.code})`,
              value: String(dept.id)
            }))}
            placeholder="请选择部门"
          />
        </FormItem>
      </Form>
    </Dialog>
  );
};

export default EditDialog; 